<template>
  <div>
    <el-dialog
      :title="modelData.id ? '编辑员工' : '新增员工'"
      :visible.sync="dialogVisible"
      @close="dialogVisibleClose"
      lock-scroll
      width="800px"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <span slot="title" class="dialog_title">{{ modelData.id ? '编辑员工' : '新增员工' }}</span>
      <div class="dialog_div_new">
        <el-form :model="modelData" :rules="rules" ref="ruleForm" class="demo-ruleForm">
          <el-row :gutter="24" style>
            <el-col :span="12">
              <el-form-item label="姓名" prop="realname">
                <el-input v-model="modelData.realname" @blur="getNameToPinying"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="modelData.sex" style="width: 100%;">
                  <el-option
                    v-for="item in sexOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12">
              <el-form-item label="出生年月" prop="name">
                <el-date-picker
                  v-model="modelData.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="婚姻状况" prop="name">
                <j-dict-select-tag
                  type="select"
                  dictCode="marital_status"
                  style="width:100%;"
                  v-model="modelData.maritalStatus"
                ></j-dict-select-tag>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12">
              <el-form-item label="人员编号" prop="name">
                <el-input v-model="modelData.personNo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拼音码" prop="name">
                <el-input v-model="modelData.pinYinCode"></el-input>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12">
              <el-form-item label="所属部门" prop="name">
                <div class="custom_select_head">
                  <el-select
                    v-model="modelData.userDeptId"
                    style="width:100%;"
                    filterable
                    ref="deptSelect"
                    @change="$forceUpdate()"
                  >
                    <el-option
                      v-for="item in deptOptions"
                      :key="item.id"
                      :label="item.deptName"
                      :value="item.id"
                    ></el-option>
                    <el-option key label value>
                      <div class="custom_add" @click.stop="onAddDeptTree">
                        <i class="el-icon-plus"></i>
                        <span>新增</span>
                      </div>
                    </el-option>
                  </el-select>
                  <div class="custom_more">
                    <i class="el-icon-more" @click.stop="onShowTree"></i>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务岗位" prop="name">
                <div class="custom_select_head">
                  <el-select v-model="modelData.userPostId" style="width:100%;" filterable>
                    <el-option
                      v-for="item in postList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                    <el-option key label value>
                      <div class="custom_add" @click.stop="onAddJobRoleRow('post')">
                        <i class="el-icon-plus"></i>
                        <span>新增</span>
                      </div>
                    </el-option>
                  </el-select>
                  <div class="custom_more">
                    <i class="el-icon-more" @click.stop="onOpenJobRole('post')"></i>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12">
              <el-form-item label="角色" prop="name">
                <div class="custom_select_head">
                  <el-select v-model="modelData.userRoleId" style="width:100%;" filterable multiple @change="handleRoleChange">
                    <el-option
                      :disabled="!isAdminUser && item.roleCode == 'admin'"
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id"
                    ></el-option>
                    <el-option key label value>
                      <div class="custom_add" @click.stop="onAddJobRoleRow('role')">
                        <i class="el-icon-plus"></i>
                        <span>新增</span>
                      </div>
                    </el-option>
                  </el-select>
                  <div class="custom_more">
                    <i class="el-icon-more" @click.stop="onOpenJobRole('role')"></i>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idNumber">
                <el-input v-model="modelData.idNumber"></el-input>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12">
              <el-form-item label="手机" prop="phone">
                <el-input
                  v-model="modelData.phone"
                  :disabled="modelData.id && modelData.id.length > 0"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="name">
                <el-input v-model="modelData.telephone"></el-input>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12">
              <el-form-item label="现住址" prop="name">
                <el-input v-model="modelData.currentAddress"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="家庭住址" prop="name">
                <el-input v-model="modelData.homeAddress"></el-input>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <el-col :span="12" v-show="false">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="modelData.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!modelData.id || modelData.id.length <= 0">
              <el-form-item label="密码" prop="password">
                <el-input v-model="modelData.password" :disabled="false"></el-input>
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row :gutter="24">-->
            <div v-if="!modelData.id || modelData.id.length <= 0">
              <el-col :span="12">
                <el-form-item label="入职时间" prop="name">
                  <el-date-picker
                    v-model="modelData.entryDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    style="width:100%;"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="员工状态" prop="name">
                  <div>
                    <el-checkbox v-model="online">在职</el-checkbox>
                    <el-checkbox v-model="offline">离职</el-checkbox>
                  </div>
                </el-form-item>
              </el-col>
            </div>
            <div v-else>
              <el-col :span="12">
                <el-form-item label="员工状态" prop="name">
                  <div>
                    <el-checkbox v-model="online">在职</el-checkbox>
                    <el-checkbox v-model="offline">离职</el-checkbox>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入职时间" prop="name">
                  <el-date-picker
                    v-model="modelData.entryDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    style="width:100%;"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </div>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="登录状态" prop="name">
                <el-checkbox v-model="modelData.isAllowLogin">
                  <span style="color:#FD6C21;">允许登录账套</span>
                </el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input style="height: 70px;" type="textarea" v-model="modelData.backup"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item class="bottom_item">
                <el-button type="primary" @click.stop="onAddSubmit">保存</el-button>
                <el-button @click.stop="dialogVisible = false">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- <div class="dialog_bottom">
          <el-button type="primary" @click.stop="onAddSubmit">保存</el-button>
          <el-button @click.stop="dialogVisible = false">取消</el-button>
        </div>-->
      </div>
    </el-dialog>
    <!-- 选择类别 -->
    <DialogTree ref="treeRef" @onSelectTree="onSelectTree"></DialogTree>
    <!-- 职务/角色选择 -->
    <DialogJobRole
      ref="jobRoleRef"
      :toJobRole="toJobRole"
      @onAddSubmit="onAddJobRole"
      @onSelect="onSelectJobRole"
    ></DialogJobRole>
    <!-- 职务/角色新增 -->
    <DialogJobRoleAdd
      ref="jobRoleAddRef"
      :toJobRoleData="toJobRoleData"
      @onAddSubmit="onAddJobRole"
    ></DialogJobRoleAdd>
    <!-- 新增树形结构数据弹框 -->
    <el-dialog title="部门" :visible.sync="showNewTree" width="480px">
      <NewCategory
        :newTreeData="newTreeData"
        @onSaveTreeChanges="onSaveTreeChanges"
        @onCancelTree="showNewTree = false"
      ></NewCategory>
    </el-dialog>
  </div>
</template>

<script>
import DialogTree from './dialogTree'
import DialogJobRole from './dialogJobRole'
import DialogJobRoleAdd from './dialogJobRoleAdd'
import { postAction, getAction, httpAction } from '@/api/manage'
import { USER_INFO } from '@/store/mutation-types'
import NewCategory from '@/components/c_category/NewCategory'
import Vue from 'vue';

export default {
  components: {
    DialogTree,
    DialogJobRole,
    DialogJobRoleAdd,
    NewCategory
  },
  props: {
    newData: {
      type: Object,
      default: () => ({
        realname: '',
        sex: '',
        birthday: '',
        maritalStatus: '',
        personNo: '',
        pinYinCode: '',
        userDeptId: '', //员工部门id
        deptName: '',
        userRoleId: '', //角色id
        roleName: '',
        userPostId: '', //职务岗位id
        postName: '',
        idNumber: '',
        phone: '',
        telephone: '',
        currentAddress: '',
        homeAddress: '',
        isResign: 0,
        entryDate: '',
        backup: '',
        isAllowLogin: true, //允许登录账套
        username: '',
        password: '',
      }),
    },
  },
  data () {
    return {
      isResignArr: [0],
      sexOptions: [
        {
          label: '男',
          value: 1,
        },
        {
          label: '女',
          value: 2,
        },
      ],
      toJobRole: '',
      toJobRoleData: {
        addOrEdit: '',
        jobOrRole: '',
      },
      // 传递给选择类别的数据
      toTreeData: {
        module: {
          name: 'deptName', //类别名称字段
          code: 'sectionCode', //类别编码字段
          pyCode: 'pinyinCode', //类别拼音码字段
          indexCode: 'indexCode', //类别排序码字段
          pid: 'parentId', //父级id字段
        },
        getTreeUrl: '/dept/xghAccountBookDept/getDeptByAbId', //获取类别接口
        deleteTreeUrl: '/xgh/section/deleteById', //删除类别接口
        addTreeUrl: '/xgh/section/add', //新增类别接口
        editTreeUrl: '/xgh/section/edit', //修改类别接口
      },
      dialogVisible: false,
      online: true,
      offline: false,
      rules: {
        realname: [{ required: true, message: '请输入员工姓名', trigger: ['blur', 'change'] }],
        idNumber: [
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号!' },
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: ['blur', 'change'] },
          { pattern: /^1[3|4|5|6|7|8|9]\d{9}$/, message: '请输入正确的手机号!' },
        ],
        // username: [
        // { required: true, message: '请输入手机号码', trigger: ['blur', 'change'] },
        //   { pattern: /^1[3|4|5|6|7|8|9]\d{9}$/, message: '请输入正确的手机号!' },
        // ],
        password: [
          { required: true, min: 6, message: '请输入最少6位的密码!', trigger: ['blur', 'change'] },
        ]
      },
      deptOptions: [],
      roleList: [],
      postList: [],
      showNewTree: false,
      // 传递数据给新增树形结构组件
      newTreeData: {
        parentData: '',
        data: '',
        state: '',
        module: {
          name: ''
        }
      },
      modelData: {
        realname: '',
        sex: '',
        birthday: '',
        maritalStatus: '',
        personNo: '',
        pinYinCode: '',
        userDeptId: '', //员工部门id
        deptName: '',
        userRoleId: '', //角色id
        roleName: '',
        userPostId: '', //职务岗位id
        postName: '',
        idNumber: '',
        phone: '',
        telephone: '',
        currentAddress: '',
        homeAddress: '',
        isResign: 0,
        entryDate: '',
        backup: '',
        isAllowLogin: true, //允许登录账套
        username: '',
        password: '',
      },
      isAdminUser: false
    }
  },
  watch: {
    dialogVisible (val) {
      if (val == true) {
        this.offline = this.modelData.isResign == 1
        this.online = !this.offline
        this.getSelectList()
      } else {
        this.resetNewData()
        // this.$refs.ruleForm.resetFields()
        // this.$destroy()
      }
    },
    online (val) {
      if (val) {
        this.modelData.isResign = 0
        this.offline = false
      } else if (this.modelData.isResign == 0 && !val) {
        this.online = true
      }
    },
    offline (val) {
      if (val) {
        this.modelData.isResign = 1
        this.online = false
      } else if (this.modelData.isResign == 1 && !val) {
        this.offline = true
      }
    },
    newData () {
      this.modelData = JSON.parse(JSON.stringify(this.newData))
    }
  },
  methods: {
    // 获取角色列表
    async getRoleList(userId) {
      try {
        const res = await postAction('role/xghAccountBookRole/getAbRoleListByAbIdAndUserId', {
          userId: userId,
        });
        if (res.code === 200) {
          return res.result;
        }
        console.error('获取角色列表失败:', res.message);
        return [];
      } catch (error) {
        console.error('获取角色列表时发生错误:', error);
        return [];
      }
    },
    // 获取角色代码
    getRoleCode(roleOptions, roleId) {
      for (let index = 0; index < roleOptions.length; index++) {
        const element = roleOptions[index];
        if (element.id === roleId) {
          return element.roleCode;
        }
      }
      return '';
    },
    // 判断用户是否为管理员
    async checkIsAdmin() {
      try {
        const userInfo = Vue.ls.get(USER_INFO);
        if (!userInfo) {
          return false;
        }
        const userId = userInfo.id;
        const roleOptions = await this.getRoleList(userId);
        const roleId = roleOptions.length > 0 ? roleOptions[0].id : '';
        const roleCode = this.getRoleCode(roleOptions, roleId);
        return roleCode === 'admin';
      } catch (error) {
        console.error('判断管理员权限出错:', error);
        return false;
      }
    },
    resetNewData () {
      this.modelData = this.$options.data().modelData
    },
    handleClose (done) {
      this.$refs.ruleForm.resetFields()
      done()
    },
    getSelectList (type) {
      if (type == 'role' || !type) {
        //角色
        getAction('/role/xghAccountBookRole/list', {}).then((res) => {
          if (res.code === 200) {
            this.roleList = res.result
            // this.tableData.forEach((item) => {
            //   item['name'] = item.roleName
            // })
            // 如果是新增,默认选中管理员角色
            if(!this.modelData.id) {
              const adminRole = this.roleList.find(role => role.roleCode === 'admin')
              if(adminRole) {
                this.modelData.userRoleId = [adminRole.id]
              }
            }
          }
        })
      }
      if (type == 'dept' || !type) {
        // 所属部门
        getAction('/dept/xghAccountBookDept/getDeptByAbId', {}).then((res) => {
          if (res.code === 200) {
            this.deptOptions = res.result
          }
        })
      }
      if (type == 'post' || !type) {
        // 职位
        getAction('/post/xghAccountBookPost/getByAccountBookId', {}).then((res) => {
          if (res.code === 200) {
            this.postList = res.result
          }
        })
      }
    },
    isResignChange (e) {
      console.log(e);
      // if (e && e.length == 1) {
      //   this.isResignArr = [e[0]]
      // } else {
      //   this.isResignArr = [e[1]]
      // }
    },
    onAddJobRoleRow (type) {
      this.toJobRoleData = {
        addOrEdit: 'add',
        jobOrRole: type,
        list: {},
      }
      this.$refs.jobRoleAddRef.modelData = {}
      this.$refs.jobRoleAddRef.dialogVisible = true
    },
    onAddJobRole (data, type) {
      console.log(type);
      this.getSelectList(type)
    },
    onAddDeptTree () {
      console.log('onAddDeptTree');
      this.newTreeData = {
        data: { id: '0' },
        state: 'add',
        module: {
          name: 'deptName', //类别名称字段
          code: 'deptCode', //类别编码字段
          pyCode: 'pinYinCode', //类别拼音码字段
          indexCode: 'backup', //备注字段
        },
        getTreeUrl: '/dept/xghAccountBookDept/getDeptByAbId', //获取类别接口
        deleteTreeUrl: '/xgh/section/deleteById', //删除类别接口
        addTreeUrl: '/dept/xghAccountBookDept/add', //新增类别接口
        editTreeUrl: '/xgh/section/edit', //修改类别接口
      }
      this.$refs.deptSelect.blur()
      this.showNewTree = true
    },
    // 新增部门回调
    onSaveTreeChanges () {
      this.getSelectList('dept')
      this.showNewTree = false
    },
    // 打开选择部门弹出框
    onShowTree (e) {
      this.$refs.treeRef.getTreeData(this.toTreeData)
      this.$refs.treeRef.dialogVisible = true
    },
    // 选择当前部门
    onSelectTree (val) {
      this.modelData.deptName = val.deptName
      this.modelData.userDeptId = val.id
      this.$forceUpdate()
    },
    // 打开选择弹框
    onOpenJobRole (val) {
      this.toJobRole = val
      this.$refs.jobRoleRef.dialogVisible = true
    },
    // 获取选择职务/角色的值
    onSelectJobRole (val, state) {
      if (state == 'role') {
        let ids = []
        let names = []
        val.forEach((item) => {
          ids.push(item.id)
          names.push(item.name)
        })
        this.modelData.userRoleId = ids //.toString()
        this.modelData.roleName = names.toString()
      } else {
        this.modelData.userPostId = val.id
        this.modelData.postName = val.name
      }
      this.$forceUpdate()
    },
    // 转换拼音码
    getNameToPinying (event) {
      this.modelData.pinYinCode = this.$pinyin.getJp(event.target.value)
    },
    onAddSubmit () {
      console.log(this.modelData);
      this.modelData.username = this.modelData.phone
      var that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = {
            ...that.modelData,
            isAllowLogin: that.modelData.isAllowLogin ? 1 : 0,
            userRoleId: that.modelData.userRoleId && that.modelData.userRoleId.toString() || ''
          }
          this.$emit('onAddSubmit', data)
        } else {
          this.$elMessage.error('请完善表单信息')
        }
      });
      // if (!data.realname) {
      //   this.$elMessage.error('姓名不能为空')
      //   return
      // } else if (!data.userDeptId) {
      //   this.$elMessage.error('部门不能为空')
      //   return
      // } else if (!data.userPostId) {
      //   this.$elMessage.error('职务不能为空')
      //   return
      // } else if (!data.userRoleId) {
      //   this.$elMessage.error('角色不能为空')
      //   return
      // } else if (!data.username) {
      //   this.$elMessage.error('用户名不能为空')
      //   return
      // } else if (!data.phone) {
      //   this.$elMessage.error('手机号不能为空')
      //   return
      // }

      // this.dialogVisible = !this.dialogVisible
      // this.$emit('onAddSubmit', data)
    },
    // 关闭事件发射
    dialogVisibleClose () {
      this.$emit('dialogVisibleClose')
    },
    handleRoleChange (value) {
      console.log('value',value)
      const adminRole = this.roleList.find(item => item.roleCode === 'admin');
      if (adminRole && !value.includes(adminRole.id)) {
        // 如果移除了管理员角色，添加管理员角色
        this.modelData.userRoleId = [...value, adminRole.id];
      }
    }
  },
  async created() {
    this.isAdminUser = await this.checkIsAdmin();
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__inner {
  height: 30px;
  line-height: 30px;
}

::v-deep .el-form-item__error {
  top: 34px !important;
}

::v-deep .el-form-item {
  display: flex;
  align-items: center;
  width: 100%;
  height: 30px;
  // margin: 6px 0;

  .el-form-item__label {
    width: auto;
    min-width: 65px;
    line-height: 30px;
    font-size: 13px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #666;
    text-align: justify;
    text-justify: distribute-all-lines;
    /*ie6-8*/
    text-align-last: justify;
    /* ie9*/
    -moz-text-align-last: justify;
    /*ff*/
    -webkit-text-align-last: justify;
    /*chrome 20+*/
    position: relative;

    &::before {
      position: absolute;
      right: 0;
      margin-right: 0;
      color: #ff0000;
      font-weight: 600;
    }
  }

  .el-form-item__content {
    flex: 1;
  }

  .el-textarea__inner {
    margin-top: 10px;
  }
}

::v-deep .el-button {
  width: 60px;
  height: 30px;
  padding: 0;
  margin-right: 15px;
  margin-left: 0;
}

.dialog_title {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 600;
  line-height: 22px;
  color: #666666;
}

.dialog_div_new {
  // width: 100%;
  padding: 10px 20px;
  // margin: -20px 0;
  // height: 60vh;
  overflow: auto;
  background: #fff;
}

.bottom_item {
  margin: 15px 0;
  width: 100%;
  text-align: center;
}

.custom_select_head {
  // right: 10px;
  width: 100%;
  height: 100%;
  position: relative;
}

.custom_more {
  position: absolute;
  right: 10px;
  z-index: 10;
  top: 6px;
  background: #fff;
  height: 28px;
  display: flex;
  align-items: center;
  color: #bfbfbf;
}

.custom_add {
  display: flex;
  justify-content: center;
  align-items: center;

  span {
    margin-left: 5px;
    color: #666666;
  }

  i {
    color: #666666;
  }
}

.cus_div {
  display: flex;
  align-items: center;
  margin-left: 5px;
}
::v-deep .el-dialog {
  .el-dialog__body {
    padding: 10px 20px;
  }
}
</style>
